package hydrap2p.servicemanager.listen;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import hydrap2p.ServiceLocation;
import hydrap2p.servicemanager.ServiceListener;

public class ThriftListener implements Listener {

	private ServiceLocation location;
	private ServiceListener.Iface listener;
	
	public ThriftListener(ServiceLocation listenerloc)
	{
		this.location=listenerloc;
	}
	
	public void connect() throws TException
	{
		TTransport transport = new TSocket(location.address,location.port);
		transport.open();
		listener=new ServiceListener.Client(new TBinaryProtocol(transport));
		for (String temp : listener.supportedInterfaces())
		{
			System.out.println("Client supports "+temp+" ?"+temp.equals("ServiceListener"));
		}
		if (!listener.supportedInterfaces().contains("ServiceListener"))
			throw new TException("Invalid Listener, missing ServiceListener");
	}

	@Override
	public void stop() {
		// Do nothing
	}


	@Override
	public int hashCode()
	{
		return location.hashCode();
	}
	
	@Override
	public boolean equals(Object obj)
	{
		if (obj instanceof ThriftListener)
		{
			ThriftListener other = (ThriftListener) obj;
			return other.location.equals(this.location);
		}
		return false;
	}

	@Override
	public void newService(String name, ServiceLocation location) throws TException {
		listener.newService(name, location);
	}

	@Override
	public void delService(String name) throws TException {
		listener.delService(name);
	}
}
